#!/usr/bin/env python
# coding: utf-8

# In[1]:


INTEGER, PLUS, EOF = 'INTERGER', 'PLUS', 'EOF'


# In[2]:


class Token:
    """记号类
    """
    def __init__(self, value_type, value):
        self.value_type = value_type # 记号的类型
        self.value = value # 记号的值
    
    def __str__(self):
        """重写查看记号内容的方法"""
        return f"Token({self.value_type}, {self.value})"
    
    def __repr__(self):
        return self.__str__()


# In[3]:


class Interpreter:
    """解释器类
    """
    def __init__(self, text):
        self.text = text
        self.position = 0
        self.current_token = None
    
    def error(self):
        raise Exception('警告：错误的输入内容！')
    
    def get_next_token(self):
        text = self.text
        if self.position >= len(text):
            return Token(EOF, None)
        current_char = text[self.position]
        if current_char.isdigit():
            token = Token(INTEGER, int(current_char))
            self.position+=1
            return token
        if current_char == '+':
            token = Token(PLUS, current_char)
            self.position+=1
            return token
        self.error()
    
    def eat(self, token_type):
        if self.current_token.value_type == token_type and self.current_token.value_type != EOF:
            self.current_token = self.get_next_token()
        elif self.current_token.value_type == EOF:
            pass
        else:
            self.error()
    
    def expr(self):
        self.current_token = self.get_next_token()
        left = self.current_token
        self.eat(INTEGER)
        
        operator = self.current_token
        if self.current_token.value_type == PLUS:
            self.current_token = self.get_next_token()
        else:
            self.error()
        
        right = self.current_token
        self.eat(INTEGER)
        
        self.eat(EOF)
        
        return left.value + right.value
    


# In[6]:


def main():
    text = "4+2"
    interpreter = Interpreter(text)
    result = interpreter.expr()
    print(text, "=", result)


# In[7]:


main()

